package com.example.demo;



import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.RateLimiter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.PrimitiveIterator;
import java.util.concurrent.TimeUnit;


@RestController("consumer")
@Slf4j
public class ServiceController {

    @Autowired
    private ProviderService providerService;
    /**
     * 每秒放行10个请求
     */
    RateLimiter rateLimiter = RateLimiter.create(10);
    private  static Integer orderNum = 1000;
    /**
     * 获取所有服务
     */
    @RequestMapping("/services")
    public Object services() {
        return providerService.hello();
    }

    /**
     * 乐观锁更新库存 + 令牌桶限流
     * @return
     */
    @RequestMapping("createOptimisticOrder")
    @ResponseBody
    public String createOptimisticOrder() {
        log.info("等待时间" + rateLimiter.acquire());
        // 非阻塞式获取令牌
//        if (!rateLimiter.acquire()) {
//            log.warn("你被限流了，真不幸，直接返回失败");
//            return "购买失败，库存不足";
//        }
        try {
            orderNum = orderNum -1;
            log.info("购买成功，剩余库存为: [{}]", orderNum);
        } catch (Exception e) {
            log.error("购买失败：[{}]", e.getMessage());
            return "购买失败，库存不足";
        }
        return String.format("购买成功，剩余库存为：%d", orderNum);
    }
}
